package com.kaibes.module.jwt.api;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.core.spring.proxy.Proxy;
import com.kaibes.module.jwt.dto.LoginQ;
import com.kaibes.module.jwt.dto.LoginResponse;
import com.kaibes.module.jwt.dto.LoginResultEnum;
import com.kaibes.module.jwt.service.AccountService;
import com.kaibes.module.jwt.service.SecurityService;
import com.kaibes.module.jwt.util.JwtUtils;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/tokens")
public class JwtApi {

    @Proxy
    private AccountService accountService;
    @Proxy
    private SecurityService securityService;
    
    @ApiLink(value = "获取一个token", validated = false)
    @PostMapping
    public ResponseEntity<LoginResponse> createToken(@RequestBody @Validated LoginQ loginQ) {
        LoginResponse response = new LoginResponse();
        boolean flag = accountService.checkAccount(loginQ.getUsername());
        if (!flag) {
            response.setResult(LoginResultEnum.WRONG_USERNAME);
            return ResponseFactory.postFailure(response, "登录失败，用户不存在");
        }
        flag = accountService.checkPassword(loginQ.getPassword());
        if (!flag) {
            response.setResult(LoginResultEnum.WRONG_PASSWORD);
            return ResponseFactory.postFailure(response, "登录失败，密码错误");
        }
        int userId = accountService.getUserId();
        String token = JwtUtils.createToken(userId, loginQ.getUsername(), securityService.listAuthoritiesByUserId(userId));
        response.setToken(token);
        response.setResult(LoginResultEnum.OK);
        return ResponseFactory.postSuccess(response, "登录成功");
    }
    
}
